package cn.itcast.aspect;

import cn.itcast.mapper.EmpLogMapper;
import cn.itcast.pojo.Emp;
import cn.itcast.pojo.EmpLoginLog;
import cn.itcast.pojo.LoginVO;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;

@Aspect
@Component
public class EmpLogAspect {
    @Autowired
    private EmpLogMapper empLogMapper;


    @Around("execution(* cn.itcast.service.EmpService.login(..))")
    public Object EmpLogAspect(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        long end = 0;
        Object result = null;
        long constTime = 0;

        try {
            result = pjp.proceed();
            return result;

        } finally {
            end = System.currentTimeMillis();
            constTime = end - start;

            EmpLoginLog empLog = new EmpLoginLog();
            empLog.setCostTime(constTime);

            // 获取登录参数
            Emp emp = (Emp) pjp.getArgs()[0];
            empLog.setUsername(emp.getUsername());
            empLog.setPassword(emp.getPassword());
            empLog.setLoginTime(LocalDateTime.now());

            // 安全地处理返回结果
            if (result instanceof LoginVO) {
                LoginVO loginVO = (LoginVO) result;
                if (loginVO != null && loginVO.getToken() != null && !loginVO.getToken().isEmpty()) {
                    empLog.setIsSuccess(1);
                    empLog.setJwt(loginVO.getToken());
                } else {
                    empLog.setIsSuccess(0);
                    empLog.setJwt(null);
                }
            } else {
                // 登录失败情况
                empLog.setIsSuccess(0);
                empLog.setJwt(null);
            }

            // 插入日志记录
            empLogMapper.insertLog(empLog);
        }
    }

}
